package com.smm.application;

import java.awt.Cursor;
import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JFileChooser;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import uk.ac.shef.wit.simmetrics.similaritymetrics.AbstractStringMetric;
import uk.ac.shef.wit.simmetrics.similaritymetrics.BlockDistance;
import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein;
import uk.ac.shef.wit.simmetrics.similaritymetrics.MongeElkan;

import com.alee.laf.WebLookAndFeel;
import com.smm.actions.GetFilesListener;
import com.smm.actions.OnClose;
import com.smm.appdata.AppData;
import com.smm.background.BackgroundProcess;
import com.smm.gui.Screen;
import com.smm.model.FileInfoVO;
import com.smm.service.OMDBapiService;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;

public class SimpleMovieManager {

	private FileInfoVO fileInfoVO = new FileInfoVO();
	private OMDBapiService service = new OMDBapiService();
	private AppData appData;
	public Screen frame;
	public static SimpleMovieManager sm;
	public static void main(String[] args) {
		sm = new SimpleMovieManager();
		sm.init();
	}
	public void init() {
		try { 
			appData = new AppData();
			WebLookAndFeel.install();
			frame = new Screen();
			frame.setVisible(true);
			updateTree();
			invokeListeners();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void startBackgroundProcess() {
		Thread bProcess = new Thread(new BackgroundProcess(frame));
		bProcess.start();
	}
	public void invokeListeners() {
		frame.tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent arg0) {
				frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) frame.tree
						.getLastSelectedPathComponent();
				if (node.isLeaf()) {
					//System.out.println(node.getUserObject().toString());
					//System.out.println(service.splitSearch(node.getUserObject().toString()));
					updateLocalRepo(node.getUserObject().toString());
					frame.progressBar.setValue(0);
				}
				frame.setCursor(Cursor.getDefaultCursor());
			}
		});
		frame.btnAdd.addActionListener(new GetFilesListener(frame, sm));
		
		frame.addWindowListener(new OnClose());
	}
	public void getSearchFolder(String path) {
		File root = new File(path);
		File[] list = root.listFiles();
		if (list == null)
			return;
		for (File f : list) {
			if (f.isDirectory()) {
				getSearchFolder(f.getAbsolutePath());
			} else {
				if (f.getAbsoluteFile().getName().contains(".mp4")
						|| f.getAbsoluteFile().getName().contains(".avi")
						|| f.getAbsoluteFile().getName().contains(".mkv"))
					fileInfoVO.getMediaFiles().add(f.getAbsoluteFile());
			}
		}
	}
	public void updateTree() {
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("Movies");
		DefaultTreeModel treeData = new DefaultTreeModel(root);
		for (File file : fileInfoVO.getMediaFiles()) {
			root.add(new DefaultMutableTreeNode(file.getName()));
		}
		frame.tree.setModel(treeData);
		if(fileInfoVO.getMediaFiles().size()>0){
			startBackgroundProcess();
		}
	}
	public String choosePath() {
		final JFileChooser fileDialog = new JFileChooser();
		int returnVal = fileDialog.showOpenDialog(frame);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			java.io.File file = fileDialog.getCurrentDirectory();
			return file.getPath();
		} else {
			return "cancel";
		}
	}
	
	public void updateLocalRepo(String node){
		JSONArray jarray = service.splitSearch(node);
		HashMap<String, String> titleMap = new HashMap<String,String>();
		ArrayList<JSONObject> infoList = new ArrayList<JSONObject>();
		frame.progressBar.setValue(10);
		try {
			for(int count = 0;count<jarray.length();count++){
				frame.progressBar.setValue(frame.progressBar.getValue()+5);
				JSONObject jobj = (JSONObject) jarray.get(count);
				titleMap.put(jobj.getString("imdbID"),jobj.getString("Title"));
				//System.out.println(service.getOmdbMovieInfoResponse(jobj.getString("imdbID")));
				infoList.add(service.getOmdbMovieInfoResponse(jobj.getString("imdbID")));
				populateInfo(infoList);
				//frame.txtpnhello.setText("<p color ='white'><b>"+service.getOmdbMovieInfoResponse(jobj.getString("imdbID")).toString()+"</b></p>");
				frame.progressBar.setValue(100);

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/**
		float max = 0;
		String matchTitle ="";
		for (String title : titleMap.values()) {
            Levenshtein b = new Levenshtein();
            float result = b.getSimilarity(title, node);
            System.out.println("Evaluvating : "+title+" : "+result);
            if(max<result){
            	max = result;
            	matchTitle = title;
            }
		}
        System.out.println("selecting : "+matchTitle+" : "+max);
	*/
	}
	
	public void populateInfo(ArrayList<JSONObject> list){
		try {
			frame.progressBar.setValue(100);
			String prittyPrint = "";
			for (JSONObject jsonObject : list) {
				prittyPrint += "<h1 color ='white' style=\"padding:1px\"><b>"+"  "+jsonObject.getString("Title")+"</b></h1>";
				//"imdbRating" Genre
				prittyPrint += "<p color ='white' style=\"padding: 1px\" >"+"<b>Rating </b>: "+jsonObject.getString("imdbRating")+" <b>Genre : </b>"+jsonObject.getString("Genre")+"</p>";
				prittyPrint += "<p color ='white' style=\"padding: 1px\"><b>"+"Year : "+jsonObject.getString("Year")+"</b></p>";
				if(jsonObject.has("Plot")){
					prittyPrint += "<p color ='white' style=\"padding: 1px\">"+"Plot : "+jsonObject.getString("Plot")+"</p>";
				}
				prittyPrint += "<hr>";
			}
			frame.txtpnhello.setText(prittyPrint);
			frame.txtpnhello.setCaretPosition(0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
